#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

//函数声明
double f(double x);
double xpoint(double x1,double x2);
double root(double x1,double x2);

int main()
{
    double x1,x2,f1,f2,x;//双浮点精度

    do
    {
        cout << "Please input x1 and x2 :" << endl;
        cin >> x1 >> x2;
        f1 = f(x1);
        f2 = f(x2);
    }while(f1 * f2 > 0);//两点函数值相反保证区间内必然有一根

    x = root(x1,x2);//求近似根函数
    cout << setiosflags(ios::fixed) << setprecision(7);//固定的浮点显示，小数点后七位数字，四舍六入五成双原则
    cout << "A root is : " << x << endl;

    return 0;
}

//使用弦截法求根的函数
double f(double x)
{
    double y;
    y = x*x*x - 5*x*x + 16*x - 80;
    return y;
}

//利用公式求弦与x轴的交点
double xpoint(double x1,double x2)//求出弦与x轴的交点
{
    double f1,f2;
    f1 = f(x1);
    f2 = f(x2);

    double x;
    x = (x1*f2 - x2*f1) / (f2 - f1);
    return x;
}

//缩小区间
double root(double x1,double x2)//求近似根
{
    double x,y,y1;
    y1 = f(x1);

    do
    {
        x = xpoint(x1 , x2);
        y = f(x);

        if(y * y1 > 0)
        {
            x1 = x;
            y1 = y;
        }
        else
            x2 = x;

    } while(fabs(y) >= 0.000001); //根的精度

    return x;
}

